<?php

namespace App\Listeners;

use App\Constants\PaymentBusinessScene;
use App\Constants\Queue;
use App\Services\Java\ApiService;
use D1M\Payment\Contracts\CombinedPaymentRepositoryInterface;
use D1M\Payment\Events\PaymentFailed;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * 通知 ES 系统充值单支付失败
 */
class NotifyRechargePaymentFailed implements ShouldQueue
{

    /**
     * The name of the connection the job should be sent to.
     *
     * @var string|null
     */
    public $connection = 'redis-enhanced';

    /**
     * The name of the queue the job should be sent to.
     *
     * @var string|null
     */
    public $queue = Queue::PAYMENT_RESULT_NOTIFY_ES;

    /**
     * 发生异常时的重试次数
     *
     * @var int
     */
    public $tries = 8;

    /**
     * 发生异常时的重试间隔时间
     *
     * 间隔：3s、9s、1m、5m、30m、1h、6h、12h
     *
     * @var array
     */
    public $backoff = [3, 9, 60, 300, 1800, 3600, 21600, 43200];

    private CombinedPaymentRepositoryInterface $combinedPaymentRepository;

    private ApiService $esService;

    /**
     * @param CombinedPaymentRepositoryInterface $combinedPaymentRepository
     * @param ApiService $esService
     */
    public function __construct(
        CombinedPaymentRepositoryInterface $combinedPaymentRepository,
        ApiService $esService
    )
    {
        $this->combinedPaymentRepository = $combinedPaymentRepository;
        $this->esService = $esService;
    }

    /**
     * @param PaymentFailed $event
     * @throws Throwable
     */
    public function handle(PaymentFailed $event)
    {
        $combinedPayment = $this->combinedPaymentRepository->getById($event->id);
        if ($combinedPayment->getBusinessScene() != PaymentBusinessScene::ES_RECHARGE) {
            return;
        }

        Log::info('充值单支付失败，即将通知 ES 。组合支付单 ID：'
            . $event->id);

        $url = '/card/api/order/closeNotify';

        $data = [
            'orderNo' => $combinedPayment->getBusinessOrderNo(),
            'time' => $combinedPayment->getFinishedAt(),
        ];

        try {
            $this->esService->requestJava($url, $data, 'post');
        } catch (Throwable $e) {
            Log::error('充值单支付失败回调，请求 ES 系统发生错误，错误消息：'
                . $e->getMessage() . '，组合支付单 ID：' . $event->id);

            throw $e;
        }

        Log::info('充值单支付失败，已通知 ES 。组合支付单 ID：'
            . $combinedPayment->getId());
    }

}